package com.bestcem.xm.ticket.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.lang.Validator;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.ticket.constant.Constants;
import com.bestcem.xm.ticket.controller.param.ticket.config.CreateConfigParam;
import com.bestcem.xm.ticket.controller.param.ticket.config.NotifyConfigParam;
import com.bestcem.xm.ticket.controller.param.ticket.config.OnlyNotifyConfigParam;
import com.bestcem.xm.ticket.controller.param.ticket.config.UpdateConfigParam;
import com.bestcem.xm.ticket.controller.param.ticket.config.createParam.WayParam;
import com.bestcem.xm.ticket.controller.vo.ticket.config.*;
import com.bestcem.xm.ticket.dao.TicketNotifyConfigDao;
import com.bestcem.xm.ticket.entity.mongo.NotifySetting;
import com.bestcem.xm.ticket.entity.mongo.TicketNotifyConfig;
import com.bestcem.xm.ticket.entity.mongo.TicketRecord;
import com.bestcem.xm.ticket.enums.FollowerFilterEnum;
import com.bestcem.xm.ticket.enums.NotifyConfigModeEnum;
import com.bestcem.xm.ticket.enums.TicketNotifyConfigEventEnum;
import com.bestcem.xm.ticket.enums.TicketNotifyConfigStatusEnum;
import com.bestcem.xm.ticket.grpc.client.TicketBaseQdesGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketBaseUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.dto.qdes.QdesDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.UserDTO;
import com.bestcem.xm.ticket.service.TicketNotifyConfigService;
import com.bestcem.xm.ticket.service.convert.TicketNotifyConfigConvert;
import com.bestcem.xm.ticket.service.convert.TicketNotifyConfigMapper;
import com.bestcem.xm.ticket.task.TicketTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.bestcem.xm.ticket.enums.TicketNotifyConfigEventEnum.*;

/**
 * 工单通知配置服务
 *
 * @author jy.zhao
 * @version 1.0
 * @date 2021/8/16 16:17
 **/
@Service
@Slf4j
public class TicketNotifyConfigServiceImpl implements TicketNotifyConfigService {

    @Autowired
    private TicketNotifyConfigDao ticketNotifyConfigDao;

    @Resource
    private TicketNotifyConfigMapper ticketNotifyConfigMapper;

    @Resource
    private TicketTask ticketTask;

    @Resource
    private TicketBaseUserGrpcService ticketBaseUserGrpcService;

    @Resource
    private TicketUserGrpcService ticketUserGrpcService;

    @Resource
    private TicketBaseQdesGrpcService ticketBaseQdesGrpcService;

    @Override
    public void clearConfigSmtpId(List<String> smtpIds) {
        if (Validator.isNull(smtpIds) || smtpIds.size() == 0) {
            log.error("[ticket] 工单错误，传递的邮箱ids为空");
            return;
        }
        ticketNotifyConfigDao.clearSmtpId(smtpIds);
    }

    @Override
    public TicketNotifyConfig findById(String id) {
        TicketNotifyConfig ticketNotifyConfig = ticketNotifyConfigDao.findById(id);
        return ticketNotifyConfig;
    }

    @Override
    public TicketConfigInfoVO parseTicketNotifyConfig(TicketConfigInfoVO ticketConfig) {
        Integer emailStatus = TicketNotifyConfigStatusEnum.DISABLED.getIndex();
        NotifySettingWayVO ways = new NotifySettingWayVO();
        ways.setEmail(true);
        ways.setSms(false);
        String smtpId = ticketConfig.getSmtpId();

        List<TicketNotifyConfigVO> ticketNotifyConfigVos = ticketConfig.getTicketNotifyConfigS();
        if (CollectionUtils.isEmpty(ticketNotifyConfigVos)) {
            List<TicketNotifyConfig> allByTicketConfigId = ticketNotifyConfigDao.findAllByTicketConfigId(ticketConfig.getId());
            ticketNotifyConfigVos = ticketNotifyConfigMapper.entityList2VoList(allByTicketConfigId);
        }

        if (!CollectionUtils.isEmpty(ticketNotifyConfigVos)) {
            for (TicketNotifyConfigVO notifyConfig : ticketNotifyConfigVos) {
                // 查询跟进人信息
                List<UserDTO> userList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(notifyConfig.getCcList())) {
                    for (TicketNotifyConfigVO.RoleRegion cc : notifyConfig.getCcList()) {
                        //  get_has_perm_user_by_cc(ObjectDict({"region": ""}), cc) 获取用户
                        List<UserDTO> ccUserList = getHasPermUserByCc(Constants.BLANK, cc);
                        if (!CollectionUtils.isEmpty(ccUserList)) {
                            userList.addAll(ccUserList);
                        }
                    }
                }
                // 将上面循环中查到的用户信息添加到推送配置里
                notifyConfig.setNotifyUsers(userList);

                if (TicketNotifyConfigStatusEnum.ENABLED.getIndex().equals(notifyConfig.getStatus())) {
                    emailStatus = TicketNotifyConfigStatusEnum.ENABLED.getIndex();
                }

                // 检查通知配置中的推送方式，如果没有重新填充
                if (Objects.nonNull(notifyConfig.getWays())) {
                    ways = notifyConfig.getWays();
                } else {
                    NotifySettingWayVO temp = new NotifySettingWayVO();
                    // way在库中的email可能有1和true两种类型，这里统一成boolean类型
                    temp.setEmail(TicketNotifyConfigStatusEnum.ENABLED.getIndex().equals(emailStatus));
                    notifyConfig.setWays(temp);
                    TicketNotifyConfig entity = ticketNotifyConfigMapper.vo2Entity(notifyConfig);
                    ticketNotifyConfigDao.saveTicketNotifyConfig(entity);
                }

                if (ObjectUtils.isEmpty(smtpId) && !ObjectUtils.isEmpty(notifyConfig.getSmtpId())) {
                    smtpId = notifyConfig.getSmtpId();
                }
            }
        }

        ticketConfig.setTicketNotifyConfigS(ticketNotifyConfigVos);
        ticketConfig.setWays(ways);
        ticketConfig.setEmailStatus(emailStatus);
        ticketConfig.setSmtpId(smtpId);
        return ticketConfig;
    }

    @Override
    public TicketConfigInfoV3VO parseTicketConfigNotifyV3(TicketConfigInfoV3VO ticketConfig) {
        Integer emailStatus = TicketNotifyConfigStatusEnum.DISABLED.getIndex();
        NotifySettingWayVO ways = new NotifySettingWayVO();
        ways.setEmail(true);
        ways.setSms(false);

        List<TicketNotifyConfigVO> ticketNotifyConfigVos = ticketConfig.getTicketNotifyConfigS();
        if (CollectionUtils.isEmpty(ticketNotifyConfigVos)) {
            List<TicketNotifyConfig> allByTicketConfigId = ticketNotifyConfigDao.findAllByTicketConfigId(ticketConfig.getId());
            ticketNotifyConfigVos = ticketNotifyConfigMapper.entityList2VoList(allByTicketConfigId);
        }

        if (!CollectionUtils.isEmpty(ticketNotifyConfigVos)) {
            for (TicketNotifyConfigVO notifyConfig : ticketNotifyConfigVos) {
                // 查询跟进人信息
                List<UserDTO> userList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(notifyConfig.getCcList())) {
                    for (TicketNotifyConfigVO.RoleRegion cc : notifyConfig.getCcList()) {
                        //  get_has_perm_user_by_cc(ObjectDict({"region": ""}), cc) 获取用户
                        List<UserDTO> ccUserList = getHasPermUserByCc(Constants.BLANK, cc);
                        if (!CollectionUtils.isEmpty(ccUserList)) {
                            userList.addAll(ccUserList);
                        }
                    }
                }
                // 将上面循环中查到的用户信息添加到推送配置里
                notifyConfig.setNotifyUsers(userList);

                if (TicketNotifyConfigStatusEnum.ENABLED.getIndex().equals(notifyConfig.getStatus())) {
                    emailStatus = TicketNotifyConfigStatusEnum.ENABLED.getIndex();
                }

                // 检查通知配置中的推送方式，如果没有重新填充
                if (Objects.nonNull(notifyConfig.getWays())) {
                    ways = notifyConfig.getWays();
                } else {
                    // way在库中的email可能有1和true两种类型，这里统一成boolean类型
                    ways.setEmail(TicketNotifyConfigStatusEnum.ENABLED.getIndex().equals(emailStatus));
                    notifyConfig.setWays(ways);
                    TicketNotifyConfig entity = ticketNotifyConfigMapper.vo2Entity(notifyConfig);
                    ticketNotifyConfigDao.saveTicketNotifyConfig(entity);
                }
            }
        }

        ticketConfig.setTicketNotifyConfigS(ticketNotifyConfigVos);
        ticketConfig.setWays(ways);
        ticketConfig.setEmailStatus(emailStatus);
        return ticketConfig;
    }

    /**
     * 获取抄送用户
     * 5828
     *
     * @param region
     * @param roleRegion
     * @return
     * @author liheng
     * @date 2021/9/2 14:11
     */
    @Nullable
    private List<UserDTO> getHasPermUserByCc(String region, TicketNotifyConfigVO.RoleRegion roleRegion) {
        if (Objects.isNull(roleRegion)) {
            return new ArrayList<>();
        }

        Integer filter = roleRegion.getCcFilter();
        if (Objects.isNull(filter)) {
            filter = FollowerFilterEnum.REGION.getIndex();
        }
        List<UserDTO> userDTOS = new ArrayList<>();

        if (FollowerFilterEnum.REGION.getIndex().equals(filter)) {
            userDTOS = ticketUserGrpcService.listUsersByRole(roleRegion.getRoleId(), region, roleRegion.getRegion());

        } else if (!ObjectUtils.isEmpty(roleRegion.getCcId())) {
            userDTOS = ticketTask.getUserIsHeadquarters(Arrays.asList(roleRegion.getCcId()));
        }
        return userDTOS;

    }

    @Override
    public OnlyNotifyConfigVO parseTicketOnlyNotifyConfig(TicketConfigInfoVO ticketConfigInfoVO) {
        List<TicketNotifyConfigVO> ticketNotifyConfigs = ticketConfigInfoVO.getTicketNotifyConfigS();
        OnlyNotifyConfigVO onlyNotifyConfig = new OnlyNotifyConfigVO();
        if (CollectionUtils.isEmpty(ticketNotifyConfigs)) {
            return onlyNotifyConfig;
        }
        List<TicketNotifyConfigVO> onlyNotify = ticketNotifyConfigs.stream().filter(o -> ONLY_NOTIFY.getIndex().equals(o.getEvent())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(onlyNotify)) {
            return onlyNotifyConfig;
        }

        TicketNotifyConfigVO firstNotify = onlyNotify.get(0);
        List<TicketNotifyConfigVO.ReceiveUser> receivers = new ArrayList<>();
        // 重新查询用户信息
        if (!CollectionUtils.isEmpty(firstNotify.getReceivers())) {
            // 请求用户查询用户信息
            String userId = firstNotify.getReceivers().get(0).getId();
            if (ObjectId.isValid(userId)) {
                UserDTO user = ticketBaseUserGrpcService.getUser(userId);
                if (Objects.nonNull(user)) {
                    TicketNotifyConfigVO.ReceiveUser receiver = new TicketNotifyConfigVO.ReceiveUser();
                    receiver.setId(user.getId());
                    receiver.setUserName(user.getName());
                    receiver.setMobile(user.getMobile());
                    receiver.setEmail(user.getEmail());
                    receivers.add(receiver);
                }
            }
        }

        if (CollectionUtils.isEmpty(receivers)) {
            receivers = firstNotify.getReceivers();
        }

        onlyNotifyConfig.setId(firstNotify.getId());
        onlyNotifyConfig.setEvent(firstNotify.getEvent());
        onlyNotifyConfig.setReceiver(receivers);
        onlyNotifyConfig.setCcList(firstNotify.getCcList());

        // 消息库新增模板相关字段
        onlyNotifyConfig.setEmailSubject(firstNotify.getEmailSubject());
        onlyNotifyConfig.setEmailContent(firstNotify.getEmailContent());
        onlyNotifyConfig.setEmailTemplateId(firstNotify.getEmailTemplateId());
        onlyNotifyConfig.setSmsSubject(firstNotify.getSmsSubject());
        onlyNotifyConfig.setSmsContent(firstNotify.getSmsContent());
        onlyNotifyConfig.setSmsTemplateId(firstNotify.getSmsTemplateId());

        return onlyNotifyConfig;
    }

    @Override
    public OnlyNotifyConfigVO parseNotifyConfigForTicketConfigV3(TicketConfigInfoV3VO ticketConfigInfoVO) {
        List<TicketNotifyConfigVO> ticketNotifyConfigs = ticketConfigInfoVO.getTicketNotifyConfigS();
        OnlyNotifyConfigVO onlyNotifyConfig = new OnlyNotifyConfigVO();
        if (CollectionUtils.isEmpty(ticketNotifyConfigs)) {
            return onlyNotifyConfig;
        }
        List<TicketNotifyConfigVO> onlyNotify = ticketNotifyConfigs.stream().filter(o -> ONLY_NOTIFY.getIndex().equals(o.getEvent())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(onlyNotify)) {
            return onlyNotifyConfig;
        }

        TicketNotifyConfigVO firstNotify = onlyNotify.get(0);
        List<TicketNotifyConfigVO.ReceiveUser> receivers = new ArrayList<>();
        // 重新查询用户信息
        if (!CollectionUtils.isEmpty(firstNotify.getReceivers())) {
            // 请求用户查询用户信息
            String userId = firstNotify.getReceivers().get(0).getId();
            if (ObjectId.isValid(userId)) {
                UserDTO user = ticketBaseUserGrpcService.getUser(userId);
                if (Objects.nonNull(user)) {
                    TicketNotifyConfigVO.ReceiveUser receiver = new TicketNotifyConfigVO.ReceiveUser();
                    receiver.setId(user.getId());
                    receiver.setUserName(user.getName());
                    receiver.setMobile(user.getMobile());
                    receiver.setEmail(user.getEmail());
                    receivers.add(receiver);
                }
            }
        }

        if (CollectionUtils.isEmpty(receivers)) {
            receivers = firstNotify.getReceivers();
        }

        onlyNotifyConfig.setId(firstNotify.getId());
        onlyNotifyConfig.setEvent(firstNotify.getEvent());
        onlyNotifyConfig.setReceiver(receivers);
        onlyNotifyConfig.setCcList(firstNotify.getCcList());

        return onlyNotifyConfig;
    }

    @Override
    public List<String> initTicketNotifyConfig(String ticketConfigId, CreateConfigParam param) {
        NotifySetting.Way ways = WayParam.paramToEntity(param.getWays());
        List<NotifyConfigParam> configList = Optional.ofNullable(param.getTicketNotifyConfig()).orElse(new ArrayList<>());
        String smtpId = Optional.ofNullable(param.getSmtpId()).orElse("");
        boolean needDeal = Optional.ofNullable(param.getNeedDeal()).orElse(false);
        OnlyNotifyConfigParam onlyNotifyConfig = Optional.ofNullable(param.getOnlyNotifyConfig()).orElse(new OnlyNotifyConfigParam());
        String surveyId = param.getSurveyId();

        ArrayList<TicketNotifyConfig> ticketNotifyConfigs = new ArrayList<>();

        if (needDeal) {
            for (NotifyConfigParam config : configList) {
                TicketNotifyConfig notifyConfig = new TicketNotifyConfig();
                notifyConfig.setOrgId(param.getOrgId());
                notifyConfig.setTicketConfigId(ticketConfigId);
                notifyConfig.setInstant(true);
                notifyConfig.setMode(NotifyConfigModeEnum.EMAIL.getIndex());
                notifyConfig.setWays(ways);
                notifyConfig.setSmtpId(smtpId);
                notifyConfig.setStatus(TicketNotifyConfigStatusEnum.ENABLED.getIndex());
                notifyConfig.setEvent(config.getEvent());
                notifyConfig.setReceiverList(new ArrayList<>());
                notifyConfig.setHasReceiver(config.getHasReceiver());
                List<TicketNotifyConfig.RoleRegion> ccList = Optional.ofNullable(config.getCcList()).orElse(new ArrayList<>());
                if (CollUtil.isNotEmpty(ccList)) {
                    ccList.forEach(o -> {
                        if (StringUtils.isBlank(o.getRegion())) {
                            o.setRegion(Constants.BLANK);
                        }
                        if (StringUtils.isBlank(o.getRoleId())) {
                            o.setRoleId(Constants.BLANK);
                        }
                    });
                }
                notifyConfig.setCcList(ccList);
                notifyConfig.setHasCcList(!CollectionUtils.isEmpty(notifyConfig.getCcList()));

                notifyConfig.setHoursLimit(Optional.ofNullable(config.getHoursLimit()).orElse(0));
                notifyConfig.setCustomAttr(new TicketRecord.CustomAttr());

                // 消息库新增模板相关字段(工单)
                notifyConfig.setEmailSubject(config.getEmailSubject());
                notifyConfig.setEmailContent(config.getEmailContent());
                notifyConfig.setEmailTemplateId(config.getEmailTemplateId());
                notifyConfig.setSmsContent(config.getSmsContent());
                notifyConfig.setSmsSubject(config.getSmsSubject());
                notifyConfig.setSmsTemplateId(config.getSmsTemplateId());

                ticketNotifyConfigs.add(notifyConfig);
            }
        }

        for (TicketNotifyConfigEventEnum value : TicketNotifyConfigEventEnum.values()) {
            if (needDeal && (CREATED_TICKET.equals(value) || FOLLOW_REMIND.equals(value) || FOLLOW_OVERDUE.equals(value))) {
                // 前端会发送 0、收到工单跟进任务，1、跟进逾期前，2、跟进逾期后
                // 这三种状态的数据，在上边已手动创建，无需重复创建
                continue;
            }

            TicketNotifyConfig notifyConfig = new TicketNotifyConfig();
            notifyConfig.setOrgId(param.getOrgId());
            notifyConfig.setTicketConfigId(ticketConfigId);
            notifyConfig.setInstant(true);
            notifyConfig.setMode(NotifyConfigModeEnum.EMAIL.getIndex());
            // ticket_notify_cfg.ways = {'email': True, 'sms': False, 'feishu': False}  # 默认工单通知方式
            notifyConfig.setWays(ways);
            notifyConfig.setSmtpId(smtpId);
            notifyConfig.setStatus(TicketNotifyConfigStatusEnum.ENABLED.getIndex());
            notifyConfig.setEvent(value.getIndex());
            notifyConfig.setReceiverList(new ArrayList<>());
            notifyConfig.setCcList(new ArrayList<>());
            notifyConfig.setHasCcList(!CollectionUtils.isEmpty(notifyConfig.getCcList()));
            notifyConfig.setCustomAttr(new TicketRecord.CustomAttr());
            // 邮件提前发送时间设置
            if (value.equals(AUDIT_REMIND) || value.equals(FOLLOW_REMIND)) {
                // 默认逾期前一小时发送
                notifyConfig.setHoursLimit(1);
            }
            // 周期性发送统计类邮件
            if (value.equals(TICKETS_STATISTICS)) {
                notifyConfig.setInstant(false);
                notifyConfig.setPeriod(new ArrayList<>());
            }

            if (!needDeal) {
                // 因 初次创建的内容，会影响到前端 进通知和跟进处理 之间切换问题，
                // 故 在创建时，如果是仅通知设置，需要把 创建，逾期前，已逾期的 hasReceiver设置为True
                boolean condition = (CREATED_TICKET.equals(value) || FOLLOW_REMIND.equals(value) || FOLLOW_OVERDUE.equals(value));
                if (condition) {
                    notifyConfig.setHasReceiver(true);
                }

                // 仅通知处理
                if (value.equals(ONLY_NOTIFY)) {
                    // 请求qdes获取问卷详情 await get_project_owner_by_project_id(survey_id)
                    // 返回格式：{"id": "", "email": "", "mobile": "", "userName": ""}
                    TicketNotifyConfig.ReceiveUser receiveUser = this.getProjectOwnerByProjectId(surveyId);
                    notifyConfig.setReceiverList(Arrays.asList(receiveUser));
                    notifyConfig.setHasReceiver(Optional.ofNullable(receiveUser.getId()).isPresent());
                    List<TicketNotifyConfig.RoleRegion> ccList = onlyNotifyConfig.getCcList();
                    if (CollUtil.isNotEmpty(ccList)) {
                        ccList.forEach(o -> {
                            if (StringUtils.isBlank(o.getRegion())) {
                                o.setRegion(null);
                            }
                            if (StringUtils.isBlank(o.getRoleId())) {
                                o.setRoleId(null);
                            }
                        });
                        notifyConfig.setCcList(ccList);
                    }

                    notifyConfig.setHasCcList(CollUtil.isNotEmpty(ccList));

                    // 消息库新增模板相关字段(预警)
                    notifyConfig.setEmailSubject(onlyNotifyConfig.getEmailSubject());
                    notifyConfig.setEmailContent(onlyNotifyConfig.getEmailContent());
                    notifyConfig.setEmailTemplateId(onlyNotifyConfig.getEmailTemplateId());
                    notifyConfig.setSmsContent(onlyNotifyConfig.getSmsContent());
                    notifyConfig.setSmsSubject(onlyNotifyConfig.getSmsSubject());
                    notifyConfig.setSmsTemplateId(onlyNotifyConfig.getSmsTemplateId());
                }
            }

            ticketNotifyConfigs.add(notifyConfig);
        }
        return ticketNotifyConfigDao.batchInsert(ticketNotifyConfigs);
    }

    /**
     * 获取问卷创建人的用户信息
     *
     * @param surveyId 问卷id
     * @return
     */
    private TicketNotifyConfig.ReceiveUser getProjectOwnerByProjectId(String surveyId) {
        TicketNotifyConfig.ReceiveUser userDTO = new TicketNotifyConfig.ReceiveUser();
        QdesDTO qdesProject = ticketBaseQdesGrpcService.getQdesProject(surveyId);
        if (Objects.isNull(qdesProject)) {

            log.error("[ticket]: Project " + surveyId + "not found");

            return userDTO;
        }
        String creator = qdesProject.getCreator();
        if (StringUtils.isNotBlank(creator)) {
            UserDTO user = ticketBaseUserGrpcService.getUser(creator);
            if (Objects.isNull(user)) {
                log.error("[ticket]:UserId " + creator + " not found user");
                return userDTO;
            }
            userDTO.setId(user.getId());
            userDTO.setEmail(user.getEmail());
            userDTO.setMobile(user.getMobile());
            userDTO.setUserName(user.getUserName());
        }

        return userDTO;
    }

    @Override
    public ServiceResult<List<TicketNotifyConfig>> updateNotifyConfig(String ticketConfigId, UpdateConfigParam param) {
        List<NotifyConfigParam> ticketNotifyConfig = param.getTicketNotifyConfig();

        NotifySetting.Way ways = WayParam.paramToEntity(param.getWays());
        String smtpId = param.getSmtpId();
        boolean needDeal = Optional.ofNullable(param.getNeedDeal()).orElse(false);
        // 预警通知配置
        OnlyNotifyConfigParam onlyNotifyConfigParam = Optional.ofNullable(param.getOnlyNotifyConfig()).orElse(new OnlyNotifyConfigParam());
        List<TicketNotifyConfig> notifyConfigs = new ArrayList<>();

        if (!needDeal) {
            String id = onlyNotifyConfigParam.getId();
            if (Objects.nonNull(id) && ObjectId.isValid(id)) {
                onlyNotifyConfigParam.setEvent(null);
                TicketNotifyConfig entity = TicketNotifyConfigConvert.paramToEntity(onlyNotifyConfigParam);
                if (Objects.nonNull(entity)) {
                    entity.setWays(ways);
                    entity.setSmtpId(smtpId);
                    notifyConfigs.add(ticketNotifyConfigDao.updateNotifyConfig(id, entity));
                }
            } else {
                TicketNotifyConfig notifyConfigByIdEvent = ticketNotifyConfigDao.findNotifyConfigByIdEvent(ticketConfigId, ONLY_NOTIFY.getIndex());
                if (Objects.isNull(notifyConfigByIdEvent)) {
                    // 返回提示信息 (AppResourceError.NotFound, msg="工单流程不存在")
                    return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "工单流程不存在");
                }
                // 通知人
                List<TicketNotifyConfig.ReceiveUser> receiver = Optional.ofNullable(onlyNotifyConfigParam.getReceiver()).orElse(new ArrayList<>(2));
                notifyConfigByIdEvent.setReceiverList(receiver);
                notifyConfigByIdEvent.setHasReceiver(!CollectionUtils.isEmpty(notifyConfigByIdEvent.getReceiverList()));
                // 抄送人
                notifyConfigByIdEvent.setCcList(Optional.ofNullable(onlyNotifyConfigParam.getCcList()).orElse(new ArrayList<>()));
                notifyConfigByIdEvent.setHasCcList(!CollectionUtils.isEmpty(notifyConfigByIdEvent.getCcList()));

                notifyConfigByIdEvent.setWays(ways);
                notifyConfigByIdEvent.setSmtpId(smtpId);

                // 消息库新增模板相关字段(预警)
                notifyConfigByIdEvent.setEmailSubject(onlyNotifyConfigParam.getEmailSubject());
                notifyConfigByIdEvent.setEmailContent(onlyNotifyConfigParam.getEmailContent());
                notifyConfigByIdEvent.setEmailTemplateId(onlyNotifyConfigParam.getEmailTemplateId());
                notifyConfigByIdEvent.setSmsContent(onlyNotifyConfigParam.getSmsContent());
                notifyConfigByIdEvent.setSmsSubject(onlyNotifyConfigParam.getSmsSubject());
                notifyConfigByIdEvent.setSmsTemplateId(onlyNotifyConfigParam.getSmsTemplateId());

                notifyConfigs.add(ticketNotifyConfigDao.saveTicketNotifyConfig(notifyConfigByIdEvent));
            }
        } else {
            for (NotifyConfigParam configParam : ticketNotifyConfig) {
                TicketNotifyConfig entity = ticketNotifyConfigMapper.notifyParamToEntity(configParam);

                entity.setHasReceiver(configParam.getHasReceiver());
                if (Objects.isNull(entity.getHasReceiver())) {
                    entity.setHasReceiver(!CollectionUtils.isEmpty(entity.getReceiverList()));
                }
                entity.setHasCcList(!CollectionUtils.isEmpty(entity.getCcList()));

                String id = configParam.getId();
                if (ObjectId.isValid(id)) {
                    entity.setEvent(null);
                    entity.setWays(ways);
                    entity.setSmtpId(smtpId);
                    notifyConfigs.add(ticketNotifyConfigDao.updateNotifyConfig(id, entity));
                } else {
                    entity.setId(null);
                    entity.setTicketConfigId(ticketConfigId);
                    entity.setWays(ways);
                    entity.setSmtpId(smtpId);
                    notifyConfigs.add(ticketNotifyConfigDao.saveTicketNotifyConfig(entity));
                }
            }
        }
        return ServiceResult.success(notifyConfigs);
    }
}
